import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/task.dart';
import '../theme/app_theme.dart';

class AddTaskPage extends StatefulWidget {
  const AddTaskPage({Key? key}) : super(key: key);

  @override
  _AddTaskPageState createState() => _AddTaskPageState();
}

class _AddTaskPageState extends State<AddTaskPage> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _locationController = TextEditingController();
  final _noteController = TextEditingController();
  
  DateTime _selectedDate = DateTime.now();
  TimeOfDay _selectedTime = TimeOfDay.now();
  int _priority = 2; // 默认中等优先级
  String _category = 'Personal'; // 默认个人类别
  
  final List<String> _categories = ['Personal', 'Work', 'Meeting', 'Shopping', 'Health', 'Study', 'Events'];
  
  @override
  void dispose() {
    _titleController.dispose();
    _locationController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  Future<void> _selectDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime.now().subtract(const Duration(days: 30)),
      lastDate: DateTime.now().add(const Duration(days: 365)),
       builder: (context, child) {
        return Theme(
          data: ThemeData.light().copyWith(
            primaryColor: AppTheme.primaryColor,
            colorScheme: const ColorScheme.light(primary: AppTheme.primaryColor),
            buttonTheme: const ButtonThemeData(textTheme: ButtonTextTheme.primary),
          ),
          child: child!,
        );
      },
    );
    if (picked != null) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _selectTime() async {
    final picked = await showTimePicker(
      context: context,
      initialTime: _selectedTime,
      builder: (context, child) {
        return Theme(
          data: ThemeData.light().copyWith(
             primaryColor: AppTheme.primaryColor,
            colorScheme: const ColorScheme.light(primary: AppTheme.primaryColor),
            buttonTheme: const ButtonThemeData(textTheme: ButtonTextTheme.primary),
          ),
          child: child!,
        );
      },
    );
    if (picked != null) {
      setState(() {
        _selectedTime = picked;
      });
    }
  }

  void _saveTask() {
    if (_formKey.currentState!.validate()) {
      final taskDateTime = DateTime(
        _selectedDate.year,
        _selectedDate.month,
        _selectedDate.day,
        _selectedTime.hour,
        _selectedTime.minute,
      );

      final task = Task(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: _titleController.text.trim(),
        time: taskDateTime,
        priority: _priority,
        location: _locationController.text.trim().isEmpty 
            ? 'Home' 
            : _locationController.text.trim(),
        category: _category,
        note: _noteController.text.trim().isEmpty 
            ? null 
            : _noteController.text.trim(),
      );

      Navigator.pop(context, task);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: const Text('添加新任务', style: TextStyle(fontWeight: FontWeight.w600, color: Colors.white)),
        backgroundColor: AppTheme.primaryColor.withOpacity(0.8),
        elevation: 0,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: AppTheme.primaryGradient,
          ),
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0)],
          ),
        ),
        child: Form(
          key: _formKey,
          child: ListView(
            padding: const EdgeInsets.fromLTRB(16, 120, 16, 16),
            children: [
              _buildSectionTitle('任务标题'),
              TextFormField(
                controller: _titleController,
                decoration: _buildInputDecoration('例如：完成项目报告', Icons.edit_outlined),
                validator: (value) => (value == null || value.trim().isEmpty) ? '请输入任务标题' : null,
              ),
              const SizedBox(height: AppTheme.paddingXL),

              _buildSectionTitle('时间安排'),
              Row(
                children: [
                  _buildDateTimePicker(
                    icon: Icons.calendar_today_outlined,
                    text: DateFormat('yyyy / MM / dd').format(_selectedDate),
                    onTap: _selectDate,
                  ),
                  const SizedBox(width: AppTheme.paddingM),
                  _buildDateTimePicker(
                    icon: Icons.access_time_outlined,
                    text: _selectedTime.format(context),
                    onTap: _selectTime,
                  ),
                ],
              ),
              const SizedBox(height: AppTheme.paddingXL),

              _buildSectionTitle('优先级'),
              _buildPrioritySelector(),
              const SizedBox(height: AppTheme.paddingXL),

              _buildSectionTitle('分类'),
              DropdownButtonFormField<String>(
                value: _category,
                decoration: _buildInputDecoration('', Icons.category_outlined),
                items: _categories.map((c) => DropdownMenuItem(value: c, child: Text(c))).toList(),
                onChanged: (v) => setState(() => _category = v!),
              ),
              const SizedBox(height: AppTheme.paddingXL),

              _buildSectionTitle('地点 (可选)'),
              TextFormField(
                controller: _locationController,
                decoration: _buildInputDecoration('例如：公司、健身房', Icons.location_on_outlined),
              ),
              const SizedBox(height: AppTheme.paddingXL),

              _buildSectionTitle('备注 (可选)'),
              TextFormField(
                controller: _noteController,
                decoration: _buildInputDecoration('添加详细描述...', Icons.note_alt_outlined),
                maxLines: 3,
              ),
              const SizedBox(height: AppTheme.paddingXXL),

              ElevatedButton.icon(
                onPressed: _saveTask,
                icon: const Icon(Icons.check_circle_outline, color: Colors.white),
                label: const Text('保存任务', style: TextStyle(color: Colors.white, fontSize: AppTheme.fontSizeL, fontWeight: FontWeight.w600)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppTheme.primaryColor,
                  padding: const EdgeInsets.symmetric(vertical: AppTheme.paddingL),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(AppTheme.radiusL)),
                  elevation: 5,
                  shadowColor: AppTheme.primaryColor.withOpacity(0.4),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: AppTheme.paddingM),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeL,
          fontWeight: FontWeight.w600,
          color: AppTheme.textSecondaryColor,
        ),
      ),
    );
  }

  InputDecoration _buildInputDecoration(String hintText, IconData icon) {
    return InputDecoration(
      prefixIcon: Icon(icon, color: AppTheme.textSecondaryColor.withOpacity(0.7)),
      hintText: hintText,
      filled: true,
      fillColor: Colors.white.withOpacity(0.8),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        borderSide: BorderSide.none,
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        borderSide: const BorderSide(color: AppTheme.primaryColor, width: 2),
      ),
      contentPadding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 20.0),
    );
  }
  
  Widget _buildDateTimePicker({required IconData icon, required String text, required VoidCallback onTap}) {
    return Expanded(
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 12.0),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.8),
            borderRadius: BorderRadius.circular(AppTheme.radiusL),
          ),
          child: Row(
            children: [
              Icon(icon, color: AppTheme.primaryColor),
              const SizedBox(width: AppTheme.paddingM),
              Text(text, style: const TextStyle(fontSize: AppTheme.fontSizeM, fontWeight: FontWeight.w500)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPrioritySelector() {
    const priorities = {1: '低', 2: '中', 3: '高'};
    const colors = {1: Colors.green, 2: Colors.orange, 3: Colors.red};

    return Row(
      children: priorities.keys.map((p) {
        final isSelected = _priority == p;
        return Expanded(
          child: GestureDetector(
            onTap: () => setState(() => _priority = p),
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              margin: const EdgeInsets.symmetric(horizontal: 4),
              padding: const EdgeInsets.symmetric(vertical: 12),
              decoration: BoxDecoration(
                color: isSelected ? colors[p] : Colors.white.withOpacity(0.8),
                borderRadius: BorderRadius.circular(AppTheme.radiusL),
                boxShadow: isSelected ? [
                  BoxShadow(
                    color: colors[p]!.withOpacity(0.4),
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  )
                ] : [],
              ),
              child: Text(
                priorities[p]!,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: isSelected ? Colors.white : AppTheme.textSecondaryColor,
                  fontWeight: FontWeight.w600,
                  fontSize: AppTheme.fontSizeM,
                ),
              ),
            ),
          ),
        );
      }).toList(),
    );
  }
}